import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Popconfirm, 
  message, 
  Input, 
  Row, 
  Col,
  Typography
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  SearchOutlined 
} from '@ant-design/icons';
import UserForm from '../components/UserForm';
import { userService } from '../services/userService';

const { Title } = Typography;
const { Search } = Input;

const UserManagement = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const [searchText, setSearchText] = useState('');

  // 获取用户列表
  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await userService.getAllUsers();
      setUsers(response.data);
    } catch (error) {
      message.error('获取用户列表失败');
      console.error('获取用户列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  // 创建用户
  const handleCreate = async (userData) => {
    try {
      await userService.createUser(userData);
      message.success('用户创建成功');
      setFormVisible(false);
      fetchUsers();
    } catch (error) {
      message.error('创建用户失败');
      console.error('创建用户失败:', error);
    }
  };

  // 更新用户
  const handleUpdate = async (userData) => {
    try {
      await userService.updateUser(editingUser.id, userData);
      message.success('用户更新成功');
      setFormVisible(false);
      setEditingUser(null);
      fetchUsers();
    } catch (error) {
      message.error('更新用户失败');
      console.error('更新用户失败:', error);
    }
  };

  // 删除用户
  const handleDelete = async (id) => {
    try {
      await userService.deleteUser(id);
      message.success('用户删除成功');
      fetchUsers();
    } catch (error) {
      message.error('删除用户失败');
      console.error('删除用户失败:', error);
    }
  };

  // 打开创建表单
  const openCreateForm = () => {
    setEditingUser(null);
    setFormVisible(true);
  };

  // 打开编辑表单
  const openEditForm = (user) => {
    setEditingUser(user);
    setFormVisible(true);
  };

  // 过滤用户
  const filteredUsers = users.filter(user =>
    user.username.toLowerCase().includes(searchText.toLowerCase()) ||
    user.email.toLowerCase().includes(searchText.toLowerCase())
  );

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => openEditForm(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="page-content">
      <div className="page-header">
        <Title level={2}>用户管理</Title>
      </div>
      
      <Card className="card-container">
        <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
          <Col>
            <Search
              placeholder="搜索用户名或邮箱"
              allowClear
              style={{ width: 300 }}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              prefix={<SearchOutlined />}
            />
          </Col>
          <Col>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={openCreateForm}
            >
              新增用户
            </Button>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={filteredUsers}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      <UserForm
        visible={formVisible}
        onCancel={() => {
          setFormVisible(false);
          setEditingUser(null);
        }}
        onSubmit={editingUser ? handleUpdate : handleCreate}
        user={editingUser}
        title={editingUser ? '编辑用户' : '新增用户'}
      />
    </div>
  );
};

export default UserManagement;
